package cn.qingfeng.nio.blocking.simpleio.thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("服务端已启动，等待客户端连接...");

            while (true) { // 持续接受客户端连接
                Socket socket = serverSocket.accept();
                new Thread(() -> {
                    try (
                            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
                    ) {
                        System.out.println("客户端已连接");
                        String inputLine = "";
                        while (true) {
                            if (!((inputLine = in.readLine()) != null)) break;

                            System.out.println("收到客户端消息: " + inputLine);
                            // 这里可以处理接收到的消息，例如转发、存储等
                            out.println("服务端回复: " + inputLine); // 简单回复客户端相同的消息
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }, "thread-1").start();
            }
        } catch (IOException e) {
            System.err.println("服务端启动失败: " + e.getMessage());
        }
    }
}